<template>
  <div>
    <el-form
      ref="formRef"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="auto"
      style="width: 900px"
      label-suffix="："
    >
      <div class="property-title">{{ $t('message.kpxx') }}</div>
      <el-form-item :label="$t('message.yhxx')">
        <div class="member_wrap">
          <MemberSearch @clear="memberClear" @select="memberSelect" />
          <div class="info mt20 mb20">
            <span class="item">{{ $t('message.name') }}：{{ cardMessage.nickName || "-" }}</span>
            <span class="item">{{ $t('message.sjh') }}：{{ cardMessage.phone || "-" }}</span>
            <span
              class="item"
            >{{ $t('message.hydj') }}：{{ cardMessage.cardName || "-" }}</span>
            <span
              class="item"
            >{{ $t('message.czje') }}：{{ cardMessage.rechargeMoney || "0.00" }}</span>
            <span
              class="item"
            >{{ $t('message.zsye') }}：{{ cardMessage.giveMoney || "0.00" }}</span>
          </div>
        </div>
      </el-form-item>
      <el-form-item v-if="showMessage" :label="$t('message.ttname')" prop="company_title">
        <div style="display: flex">
          <el-select
            v-model="param.id"
            style="width: 800px"
            filterable
            :placeholder="$t('message.qxz') + $t('message.ttname')"
            @change="selectChange"
          >
            <el-option
              v-for="item in titleList"
              :key="item.id"
              :label="item.company_title"
              :value="item.id"
            />
          </el-select>
          <el-button icon="el-icon-plus" @click="addInvoiceTitle" />
        </div>
      </el-form-item>
    </el-form>
    <template v-if="showMessage">
      <div class="property-title">{{ $t('message.ddxq') }}</div>
      <div class="doumee-filter">
        <el-form inline label-suffix="：" @submit.native.prevent>
          <el-form-item :label="$t('message.ddbh')">
            <el-input
              v-model="filters.orderId"
              clearable
              :placeholder="$t('message.qsr') + $t('message.ddbh')"
            />
          </el-form-item>
          <el-form-item :label="$t('message.ddlx')">
            <el-select
              v-model="filters.orderType"
              :placeholder="$t('message.qxz') + $t('message.ddlx')"
              clearable
            >
              <el-option
                v-for="item in orderTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('message.zffs')">
            <el-select
              v-model="filters.payMethod"
              :placeholder="$t('message.qxz') + $t('message.zffs')"
              clearable
            >
              <el-option
                v-for="item in payTypes"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('message.ddje')">
            <el-input
              v-model="filters.stratAmot"
              clearable
              :placeholder="$t('message.qsr') + $t('message.ddzxje')"
            />
            <span class="ml10 mr10">~</span>
            <el-input
              v-model="filters.endAmot"
              clearable
              :placeholder="$t('message.qsr') + $t('message.ddzdje')"
            />
          </el-form-item>
        </el-form>

        <el-button
          v-preventReClick
          type="primary"
          @click="getList(1)"
        >{{ $t('message.cz') }}</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        :header-row-class-name="'table-header'"
        class="doumee-element-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column
          align="center"
          :label="$t('message.ddh')"
          min-width="220"
          prop="id"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          :label="$t('message.ddxq')"
          prop="orderInfo"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          :label="$t('message.kkpje')"
          min-width="100"
          prop="invoiceMoney"
        />
        <el-table-column
          align="center"
          :label="$t('message.ddje')"
          prop="price"
          min-width="80"
        />
        <el-table-column
          align="center"
          :label="$t('message.ddlx')"
          prop="orderType"
          min-width="100"
        />
        <el-table-column
          align="center"
          :label="$t('message.ddly')"
          prop="source"
          min-width="80"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          :label="$t('message.zffs')"
          prop="payMethod"
          min-width="100"
        />
        <el-table-column
          align="center"
          :label="$t('message.paytime')"
          prop="payTime"
          min-width="160"
        />
      </el-table>
      <div class="total_order df_ac">
        <div class="item">
          <div>{{ $t('message.yxzdd') }}</div>
          <div class="value">
            <span
              style="font-size: 16px; font-weight: 500"
            >{{ multipleSelection.length }} </span>{{ $t('message.gei') }}
          </div>
        </div>
        <div class="flex1">
          <div>{{ $t('message.zdkpjey') }}</div>
          <div
            class="value"
            style="color: orange; font-size: 16px; font-weight: 500"
          >
            {{ $t('message.rmbfh') }} {{ totalInvoiceMoney }}
          </div>
        </div>
        <el-button type="primary" @click="openEnterModal">{{ $t('message.qrkp') }}</el-button>
      </div>
      <Paginations
        :total="total"
        :page="pagination.page"
        @current-change="currentPageChange"
        @SizeChange="pageSizeChange"
      />
    </template>
    <el-dialog
      :title="$t('message.kpqr')"
      width="680px"
      :visible.sync="isShowModalSub"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
    >
      <div>
        <div class="mb30">
          <div class="text">
            <span>{{ $t('message.yx') }}</span>
            <span>{{ multipleSelection.length }}</span>
            <span>{{ $t('message.gddyjkpje') }}</span>
            <span class="secondColor">{{ totalInvoiceMoney }}</span>
          </div>
          <div class="placeholder9" style="margin-top: 4px">
            {{ $t('message.yjkpjeck') }}
          </div>
        </div>
        <el-form
          ref="ruleForm"
          class="doumee-form"
          :model="param"
          :rules="rules"
          label-width="auto"
          style="width: 600px"
          label-suffix="："
        >
          <el-form-item :label="$t('message.ttlx')" prop="type">
            <el-radio
              v-model="param.type"
              disabled
              label="0"
            >{{ $t('message.qydw') }}</el-radio>
            <el-radio
              v-model="param.type"
              disabled
              label="1"
            >{{ $t('message.grfqydw') }}</el-radio>
          </el-form-item>
          <el-form-item :label="$t('message.ttname')" prop="company_title">
            <div style="display: flex">
              <el-input
                v-model="param.company_title"
                disabled
                :placeholder="$t('message.qsr') + $t('message.ttname')"
              />
              <!-- <el-select
                v-model="param.company_title"
                style="width: 500px"
                filterable
                :placeholder="$t('message.qxz') + $t('message.ttname')"
                disabled
                @change="selectChange"
              >
                <el-option
                  v-for="item in titleList"
                  :key="item.id"
                  :label="item.company_title"
                  :value="item.id"
                />
              </el-select> -->
              <!-- <el-button icon="el-icon-plus" @click="addInvoiceTitle" /> -->
            </div>
          </el-form-item>
          <el-form-item
            v-if="param.company_tax && param.type === '0'"
            :label="$t('message.gssh')"
            prop="company_tax"
          >
            <el-input
              v-model="param.company_tax"
              disabled
              :placeholder="$t('message.gjgjzddr')"
            />
          </el-form-item>
          <el-form-item :label="$t('message.dzyx')" prop="email">
            <el-input v-model="param.email" :placeholder="$t('message.yyjsdzfp')" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowModalSub = false">{{ $t('message.qxkp') }}</el-button>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="confirmBtn"
        >{{ $t('message.qdkp') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('message.add') + $t('message.fptt')"
      :visible.sync="showAddInvoiceTitle"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
    >
      <el-form
        ref="invoiceForm"
        :model="form"
        label-width="auto"
        :rules="addrules"
      >
        <el-form-item :label="$t('message.ttlx')" prop="type">
          <el-radio v-model="form.type" label="0">{{ $t('message.qydw') }}</el-radio>
          <el-radio v-model="form.type" label="1">{{ $t('message.grfqydw') }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('message.ttname')" prop="company_title">
          <el-input v-model="form.company_title" :placeholder="$t('message.qsr') + $t('message.ttname')" />
        </el-form-item>
        <el-form-item
          v-if="form.type == '0'"
          :label="$t('message.gssh')"
          prop="company_tax"
        >
          <el-input v-model="form.company_tax" :placeholder="$t('message.qsr') + $t('message.gssh')" />
        </el-form-item>
        <el-form-item :label="$t('message.sfmr')" prop="is_default">
          <el-radio v-model="form.is_default" label="0">{{ $t('message.fou') }}</el-radio>
          <el-radio v-model="form.is_default" label="1">{{ $t('message.shi') }}</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAddInvoiceTitle">{{ $t('message.qx') }}</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="confirmAddInvoiceTitle"
        >{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import store from '@/store'
import MemberSearch from '@/components/MemberSearch'
import {
  configList,
  orderTypeList,
  VIPInfo,
  addInvoiceTitle,
  makeInvoice,
  myInvoiceTitle,
  orderInvoiceListPC
} from '@/api'

export default {
  name: 'InvoiceMember',
  components: {
    MemberSearch
  },
  data() {
    return {
      isShowModalSub: false,
      modalDialog: store.getters.dialog,
      subLoading: false,
      meta: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      orderTypeList: [],
      form: {},
      filters: {},
      param: {},
      listLoading: false,
      showMessage: false,
      showAddInvoiceTitle: false,
      cardMessage: {},
      payTypes: [],
      titleList: [],
      multipleSelection: [],
      rules: {
        cardNum: [{ required: true, message: this.$t('message.hy2'), trigger: 'blur' }],
        company_title: [{ required: true, message: this.$t('message.qsr') + this.$t('message.ttname'), trigger: 'blur' }],
        type: [{ required: true, message: this.$t('message.qxz') + this.$t('message.ttlx'), trigger: 'change' }],
        company_tax: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.gssh'), trigger: 'blur' }
        ],
        email: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.jsyx'), trigger: 'blur' },
          {
            pattern: /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/,
            message: this.$t('message.qsrzrdyx'),
            trigger: 'blur'
          }
        ]
      },
      addrules: {
        type: [{ required: true, message: this.$t('message.qxz') + this.$t('message.ttlx'), trigger: 'blur' }],
        company_title: [{ required: true, message: this.$t('message.qsr') + this.$t('message.ttname'), trigger: 'blur' }],
        company_tax: [{ required: true, message: this.$t('message.qsr') + this.$t('message.gssh'), trigger: 'blur' }],
        is_default: [{ required: true, message: this.$t('message.qxz') + this.$t('message.sfmr'), trigger: 'blur' }],
        email: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.jsyx'), trigger: 'blur' },
          {
            pattern: /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/,
            message: this.$t('message.qsrzrdyx'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    totalInvoiceMoney() {
      let total = 0
      this.multipleSelection.forEach(item => {
        total += item.invoiceMoney
      })
      return total
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.payTypesList()
    this.getOrderTypeList()
  },
  methods: {
    payTypesList() {
      configList({ param: { type: '2', code: '1' }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.payTypes = res.recordList
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取订单类型列表
    getOrderTypeList() {
      orderTypeList({
        param: {
          type: 'ORDER_TYPE_INVOICE_OPEN'
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.orderTypeList = res.recordList
          // this.$set(this.filters, 'orderType', this.orderTypeList[0].id)
        })
    },
    getMyInvoiceTitle() {
      if (!this.cardMessage.id) {
        this.$message.warning(this.$t('message.hy5'))
        return
      }
      myInvoiceTitle({
        param: {
          memberId: this.cardMessage.id
        }
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.titleList = res.recordList
            if (this.titleList.length > 0) {
              this.$set(this, 'param', res.recordList[0])
              this.titleList.forEach(item => {
                if (item.is_default === '1') {
                  // this.$set(this.param, 'email', item.email || '')
                  // this.$set(this.param, 'id', item.id || '')
                  this.$set(this, 'param', item)
                }
              })
              this.selectChange()
            }
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    memberSelect(val) {
      this.cardMessage = val
      this.showMessage = true
      this.$set(this.param, 'cardNum', val.searchValue)
      this.getMyInvoiceTitle()
      this.getList(1)
    },
    memberClear() {
      this.cardMessage = {}
      this.showMessage = false
    },
    searchAction() {
      if (!this.param.cardNum.length) {
        this.$message.error(this.$t('message.qsr') + this.$t('message.hy1'))
        return
      }
      VIPInfo({
        param: {
          phoneOrNo: this.param.cardNum
        }
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.cardMessage = res.record
            this.showMessage = true
            this.getMyInvoiceTitle()
            this.getList(1)
          }
        })
        .catch((err) => {
          console.log(err)
          this.cardMessage = {}
          this.showMessage = false
        })
    },
    closeOut() {
      this.showMessage = false
    },
    currentPageChange(val) {
      this.pagination.page = val
      this.getList()
    },
    pageSizeChange(val) {
      this.pagination.rows = val
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(11, val)
    },
    openEnterModal() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message.error(this.$t('message.qxzykjfpddd'))
        return false
      }
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.isShowModalSub = true
        }
      })
      if (!this.param.id) {
        this.$message.error(this.$t('message.qxxzttmc'))
        return false
      }
    },
    confirmBtn() {
      const multipleSelection = this.multipleSelection
      const ids = []
      multipleSelection.forEach((e) => {
        ids.push(e.id)
      })
      const param = { ...this.param, ids, memberId: this.cardMessage.id }
      param.titleId = param.id
      // param.ids =
      param.type = !param.company_tax ? '1' : '0'
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.subLoading = true
          makeInvoice({
            param
          })
            .then((res) => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.isShowModalSub = false
                this.ruleForm = {}
                this.$message.success(this.$t('message.fpkjcg'))
                this.$emit('changeTabs', '0')
              }
            })
            .catch((err) => {
              this.subLoading = false
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clearList() {
      this.filters = {}
      this.getList(1)
    },
    getList(page) {
      this.listLoading = false
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      filters.memberId = this.cardMessage.id
      pagination.firstQueryTime = parseTime(new Date())
      orderInvoiceListPC({
        pagination,
        param: {
          venueId,
          ...filters
        }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.recordList
          this.total = res.totalCount
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    selectChange() {
      const invoiceitem = this.titleList.find(item => item.id === this.param.id)
      if (invoiceitem) {
        this.param = invoiceitem
      }
      // for (const invoiceTitle of this.titleList) {
      //   if (invoiceTitle.id === this.param.id) {
      //     const item = JSON.stringify(invoiceTitle)
      //     const invoiceitem = JSON.parse(item)
      //     // this.param = invoiceitem
      //     this.param.id = invoiceitem.id
      //     this.param.company_title = invoiceitem.company_title
      //     this.param.company_tax = invoiceitem.company_tax
      //   }
      // }
    },
    addInvoiceTitle() {
      if (!this.cardMessage.id) {
        this.$message.error(this.$t('message.hy5'))
        return
      }
      this.form = {}
      this.showAddInvoiceTitle = true
    },
    confirmAddInvoiceTitle() {
      if (!this.cardMessage.id) {
        this.$message.error(this.$t('message.hy5'))
        return
      }
      this.form.memberId = this.cardMessage.id
      this.$refs.invoiceForm.validate((valid) => {
        if (valid) {
          const param = { ...this.form }
          // this.titleList.push(addform)
          addInvoiceTitle({
            param
          })
            .then((res) => {
              if (res.errorCode === '000000') {
                this.showAddInvoiceTitle = false
                this.getMyInvoiceTitle()
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancleAddInvoiceTitle() {
      this.showAddInvoiceTitle = false
      this.form = {}
    }
  }
}
</script>
<style lang="scss" scoped>
.member_wrap {
  .info {
    display: flex;
    flex-wrap: wrap;
    .item {
      width: 33.33%;
    }
  }
}
.total_order {
  border: 1px solid #e8ebf6;
  padding: 16px;
  .item {
    margin-right: 60px;
  }
  .value {
    margin-top: 4px;
  }
}
.card-message {
  margin-top: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
</style>
